package com.takeaway.servlet;

import com.jspsmart.upload.*;
import com.takeaway.const_.Const;
import com.takeaway.pojo.*;
import com.takeaway.service.serviceimpl.*;
import com.takeaway.service.serviceinterface.*;
import com.takeaway.utils.AgentManage;
import com.takeaway.utils.CreateSimpleMail;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 后台赖骏
 */
@SuppressWarnings("unused")
@WebServlet("/user/*")
public class UserServlet extends BaseServlet{
    public void upLoadImg (HttpServletRequest req, HttpServletResponse resp)throws Exception{
        SmartUpload smartUpload = new SmartUpload();
            smartUpload.initialize(this.getServletConfig(),req,resp);
            smartUpload.upload();
            Files files = smartUpload.getFiles();
            File file = files.getFile(0);
            Request request = smartUpload.getRequest();
            User user = (User) req.getSession().getAttribute("user");
            String fileName = file.getFileName();
            smartUpload.save("/images/shop");
            System.out.println(fileName);
            UserService userService = new  UserServiceImpl();
            AgentManage agentManage = new AgentManage(userService);
            UserService agent = (UserService)agentManage.getAgent();
                User user1 = agent.updateUserImg(user.getId(), fileName);
                switch (user.getRightId()) {
                    case 0:
                        req.getSession().setAttribute("user", user1);
                        req.getRequestDispatcher("../jsp/UserCenter.jsp").forward(req, resp);
                        break;
                    case 1:
                        req.getSession().setAttribute("user", user1);
                        req.getRequestDispatcher("../jsp/BusinessCenter.jsp").forward(req, resp);
                        break;
                    default:
                        break;
                }



    }
    public void forward(HttpServletRequest req, HttpServletResponse resp)throws Exception{
        String getCode = req.getParameter("get");
        String login = req.getParameter("log");
        String username = req.getParameter("username");
        req.setAttribute("username",username);
        if (getCode!=null){
                req.getRequestDispatcher("checkMail").forward(req,resp);
        }
        else {
            req.setAttribute("password",req.getParameter("password"));
                req.getRequestDispatcher("mailLogin").forward(req,resp);
        }
    }
    public void mailLogin(HttpServletRequest req, HttpServletResponse resp)throws Exception{
        UserService userService = new UserServiceImpl();
        AgentManage agentManage = new AgentManage(userService);
        UserService agent = (UserService)agentManage.getAgent();
        String mailCode1 = (String) req.getSession().getAttribute("mailCode");
        String mailCode2 = req.getParameter("password");
        String username = req.getParameter("username");
        if (mailCode1.equals(mailCode2)){
                User user = agent.checkUser(username);
                if (user !=null) {
                    switch (user.getRightId()) {
                        case Const.USER_ID:
                            if (user.getRightId() == Const.MANAGER_ID || user.getRightId() == Const.USER_ID) {
                                req.getSession().setAttribute("user", user);
                                req.getRequestDispatcher("../jsp/UserCenter.jsp").forward(req, resp);
                            } else {
                                req.setAttribute("msg", Const.LOGIN_ERROR_MSG);
                                req.getRequestDispatcher("../jsp/Msg.jsp").forward(req, resp);
                            }

                            break;
                        case Const.BUSINESS_ID:
                            if (user.getRightId() == Const.BUSINESS_ID || user.getRightId() == Const.MANAGER_ID) {
                                req.getSession().setAttribute("user", user);
                                req.getRequestDispatcher("../jsp/BusinessCenter.jsp").forward(req, resp);
                            } else {
                                req.setAttribute("msg", Const.LOGIN_ERROR_MSG);
                                req.getRequestDispatcher("../jsp/Msg.jsp").forward(req, resp);
                            }
                            break;
                        default:
                            req.setAttribute("msg", Const.LOGIN_ERROR_MSG);
                            req.getRequestDispatcher("../jsp/Msg.jsp").forward(req, resp);
                            break;
                    }

                }
                else {
                    req.setAttribute("msg", Const.LOGIN_ERROR_MSG);
                    req.getRequestDispatcher("../jsp/Msg.jsp").forward(req, resp);
                }


        }

    }
    public void checkMail(HttpServletRequest req, HttpServletResponse resp)throws Exception{
        String acceptMail = req.getParameter("username");
            String mailCode = CreateSimpleMail.sentMail(acceptMail);
            req.getSession().setAttribute("mailCode",mailCode);
            req.setAttribute("msg",Const.SENT_SUCCESS_MSG);
            req.getRequestDispatcher("../jsp/Msg.jsp").forward(req,resp);
    }
    public void addUser(HttpServletRequest req, HttpServletResponse resp)throws Exception{
        UserService userService = new UserServiceImpl();
        AgentManage agentManage = new AgentManage(userService);
        UserService agent = (UserService)agentManage.getAgent();
        String username = req.getParameter("username");
        String pwd = req.getParameter("password");
        int rightId = Integer.parseInt(req.getParameter("id"));
            int insert = agent.addUser(username, pwd, rightId);
            if (insert>0){
                req.setAttribute("msg",Const.REGISTER_SUCCESS_MSG);
                req.getRequestDispatcher("../jsp/Msg.jsp").forward(req,resp);
            }
            else {
                req.setAttribute("msg",Const.REGISTER_ERROR_MSG);
                req.getRequestDispatcher("../jsp/Msg.jsp").forward(req,resp);
            }
    }
    public void showMenu(HttpServletRequest req, HttpServletResponse resp)throws Exception{
        int shopId = Integer.parseInt(req.getParameter("shopId"));
        String startStr = req.getParameter("start");
        int start ;
        if (startStr ==null){
            start =  Const.DEFAULT_BEGIN;
        }
        else {
            start = Integer.parseInt(startStr);
        }
        FoodService foodService = new FoodServiceImpl();
        AgentManage agentManage = new AgentManage(foodService);
        FoodService agent =  (FoodService)agentManage.getAgent();
            List<Food> foods = agent.showLimitFood(start, Const.LIST_NUM, shopId);
            long rows = agent.checkFoodNum(shopId);
            req.setAttribute("rows",rows);
            req.setAttribute("shopId",shopId);
            req.setAttribute("foods",foods);
            req.getRequestDispatcher("/jsp/ShowMenu.jsp").forward(req,resp);
    }
    public void showShop(HttpServletRequest req, HttpServletResponse resp)throws Exception{
        ShopService shopService = new ShopServiceImpl();
        AgentManage agentManage = new AgentManage(shopService);
        ShopService agent =  (ShopService)agentManage.getAgent();
            List<Shop> shops = agent.showShop(Const.DEFAULT_BEGIN, Const.LIST_NUM);
            long rows = agent.checkShopNum();
            req.setAttribute("rows",rows);
            req.setAttribute("shops",shops);
            req.getRequestDispatcher("/jsp/ShowShop.jsp").forward(req,resp);

    }
    public void recharge(HttpServletRequest req, HttpServletResponse resp)throws Exception{
        String moneyStr = req.getParameter("money");
        User user = (User)req.getSession().getAttribute("user");
        double money = Double.parseDouble(moneyStr);
        UserService userService = new UserServiceImpl();
        AgentManage agentManage = new AgentManage(userService);
        UserService agent = (UserService) agentManage.getAgent();
        int recharge;

            recharge = agent.recharge(money, user);

        if (recharge == 1){
                user = agent.checkUser(user.getId());
                req.getSession().setAttribute("user",user);
                req.getRequestDispatcher("/jsp/UserCenter.jsp").forward(req, resp);
        }
        else {
            System.out.println("充值失败");
        }

    }
    public void login(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        User user = null;
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        UserService userService = new UserServiceImpl();
        AgentManage agentManage = new AgentManage(userService);
        UserService agent = (UserService)agentManage.getAgent();
            Cookie[] cookies = req.getCookies();
            if (username!=null||password!=null){
                Cookie cookie1 = new Cookie("username", username);
                cookie1.setMaxAge(60*30*1000);
                cookie1.setPath("/");
                resp.addCookie(cookie1);
                Cookie cookie2 = new Cookie("password", password);
                cookie2.setMaxAge(60*30*1000);
                cookie2.setPath("/");
                resp.addCookie(cookie2);
                user = agent.loginService(username,password);
            }
            else {
                for (Cookie c: cookies) {
                    switch (c.getName()){
                        case "username" :
                            username = c.getValue();
                            break;
                        case "password" :
                            password = c.getValue();
                            break;
                        default:
                            break;
                    }
                    user = agent.loginService(username,password);
                }
            }
        if (user!=null){
            switch (user.getRightId()) {
                case Const.USER_ID:
                    if (user.getRightId() == Const.USER_ID || user.getRightId() == Const.MANAGER_ID) {
                        req.getSession().setAttribute("user", user);
                        req.getRequestDispatcher("/jsp/UserCenter.jsp").forward(req, resp);
                    } else {
                        req.setAttribute("msg", Const.LOGIN_ERROR_MSG);
                        req.getRequestDispatcher("/jsp/Msg.jsp").forward(req, resp);
                    }

                    break;
                case Const.BUSINESS_ID:
                    if (user.getRightId()==Const.BUSINESS_ID||user.getRightId()==Const.MANAGER_ID) {
                        req.getSession().setAttribute("user", user);
                        req.getRequestDispatcher("/jsp/BusinessCenter.jsp").forward(req, resp);
                    }
                    else {
                        req.setAttribute("msg", Const.LOGIN_ERROR_MSG);
                        req.getRequestDispatcher("/jsp/Msg.jsp").forward(req, resp);
                    }
                    break;
                case Const.MANAGER_ID:
                    req.getSession().setAttribute("user", user);
                    req.getRequestDispatcher("/jsp/ManageCenter.jsp").forward(req, resp);
                    break;
                case Const.BAN_USER_ID:
                case Const.BAN_BUSINESS_ID:
                    req.getSession().setAttribute("user", user);
                    req.getRequestDispatcher("/jsp/UserComplaint.jsp").forward(req, resp);
                    break;
                default:
                    req.setAttribute("msg", Const.LOGIN_ERROR_MSG);
                    req.getRequestDispatcher("/jsp/Msg.jsp").forward(req,resp);
            }
        }
        else {
            req.setAttribute("msg", Const.LOGIN_ERROR_MSG);
            req.getRequestDispatcher("/jsp/Msg.jsp").forward(req,resp);
        }
    }

    public void addCustomerCart(HttpServletRequest req, HttpServletResponse resp)throws Exception{

        int foodId = Integer.parseInt(req.getParameter("foodId"));
        String disNum = req.getParameter("dishNum");
        FoodService foodService = new FoodServiceImpl();
        AgentManage agentManage = new AgentManage(foodService);
        FoodService agent = (FoodService)agentManage.getAgent();
            Food food = agent.checkSingleFood(foodId);
            Cookie[] cookies = req.getCookies();
            Cookie cookie =null;
            for (Cookie c: cookies) {
                if ("carts".equals(c.getName())){
                    cookie = new Cookie("carts",c.getValue()+","+food.getDishName()
                            +","+food.getDescription()
                            +","+disNum);
                    break;
                }
            }
            if (cookie == null) {
                cookie = new Cookie("carts",food.getDishName()
                        +","+food.getDescription()
                        +","+disNum);
            }
            cookie.setMaxAge(60*1000);
            cookie.setPath("/");

            resp.addCookie(cookie);
            req.setAttribute("msg",Const.ADD_SUCCESS_MSG);
            req.getRequestDispatcher("../jsp/Msg.jsp").forward(req,resp);




    }

    public void checkCustomerCart(HttpServletRequest req, HttpServletResponse resp)throws Exception{
        Cookie[] cookies = req.getCookies();
        String[] cartInfo = new String[0];
        for (Cookie c:cookies) {
            if ("carts".equals(c.getName())){
                cartInfo = c.getValue().split(",");
                break;
            }
        }
        List<String> dishNames = new ArrayList<>();
        List<String> descriptions = new ArrayList<>();
        List<String> dishNums = new ArrayList<>();
        for (int i = 0; i < cartInfo.length/3; i++) {
            dishNames.add(cartInfo[i*3]);
            descriptions.add(cartInfo[i*3+1]);
            dishNums.add(cartInfo[i*3+2]);
        }
        req.setAttribute("dishNames",dishNames);
        req.setAttribute("descriptions",descriptions);
        req.setAttribute("dishNums",dishNums);

            req.getRequestDispatcher("../jsp/checkCustomerCart.jsp").forward(req,resp);

    }

    public void checkCart(HttpServletRequest req, HttpServletResponse resp)throws Exception{
        User user = (User)req.getSession().getAttribute("user");
        if (user == null){
                req.getRequestDispatcher("checkCustomerCart").forward(req,resp);
                return;
        }
        CartService cartService = new CartServiceImpl();
        FoodService foodService = new FoodServiceImpl();
        AgentManage agentManage1 = new AgentManage(cartService);
        AgentManage agentManage2 = new AgentManage(foodService);
        CartService agent1 = (CartService)agentManage1.getAgent();
        FoodService agent2 = (FoodService)agentManage2.getAgent();

            List<Cart> carts = agent1.checkCart(user.getId());
            List<Food> foods = agent2.checkCartFood(carts);
            req.setAttribute("carts",carts);
            req.setAttribute("foods",foods);
            req.getRequestDispatcher("/jsp/Cart.jsp").forward(req,resp);
    }
    public void addBook(HttpServletRequest req, HttpServletResponse resp){
        System.out.println("addBook已执行");
        BookService bookService = new BookServiceImpl();
        AgentManage agentManage = new AgentManage(bookService);
        BookService agent = (BookService)agentManage.getAgent();
        User user = (User)req.getSession().getAttribute("user");
        String dishNumStr = req.getParameter("dishNum");
        int dishNum = Integer.parseInt(dishNumStr);
        String foodIdStr = req.getParameter("foodId");
        int foodId = Integer.parseInt(foodIdStr);
        double price;
        if (req.getAttribute("price")!=null){
            price = (double)req.getAttribute("price");
        }
        else {
            price = Double.parseDouble(req.getParameter("price"));
        }


        try {
            int i = agent.insertBook(user.getId(), foodId, dishNum, price);
            boolean autoDelete = false;
            if (req.getSession().getAttribute("autoDelete")!=null){
                autoDelete = (boolean) req.getSession().getAttribute("autoDelete");
                req.getSession().removeAttribute("autoDelete");
            }
            if (i>0){
                if (autoDelete){
                    req.getRequestDispatcher("deleteCart").forward(req,resp);
                }
                else {
                    req.setAttribute("msg",Const.BOOK_SUCCESS_MSG);
                    req.getRequestDispatcher("/jsp/Msg.jsp").forward(req,resp);
                }
            }
            else{
                req.setAttribute("msg",Const.BOOK_ERROR_MSG);
                req.getRequestDispatcher("/jsp/Msg.jsp").forward(req,resp);
            }
        } catch (Exception e) {
            e.printStackTrace();
            req.setAttribute("msg",Const.BOOK_ERROR_MSG);
            try {
                req.getRequestDispatcher("/jsp/Msg.jsp").forward(req,resp);
            } catch (ServletException | IOException ex) {
                ex.printStackTrace();
                }
            req.setAttribute("msg", Const.ILLEGAL_INPUT_MSG);

        }

    }
    public void addCart(HttpServletRequest req, HttpServletResponse resp)throws Exception{

        User user = (User)req.getSession().getAttribute("user");
        String foodIdStr = req.getParameter("foodId");
        int foodId = Integer.parseInt(foodIdStr);
        String cartNumStr = req.getParameter("dishNum");
        int cartNum = Integer.parseInt(cartNumStr);
        String shopIdStr = req.getParameter("shopId");
        int shopId = Integer.parseInt(shopIdStr);
        if (user == null){
                req.setAttribute("foodId",foodId);
                req.setAttribute("dishNum",cartNumStr);
                req.setAttribute("shopId",shopId);
                req.getRequestDispatcher("addCustomerCart").forward(req,resp);
        }
        CartService cartService = new CartServiceImpl();
        AgentManage agentManage = new AgentManage(cartService);
        CartService agent = (CartService)agentManage.getAgent();

            assert user != null;
            int addCart = agent.addCart(user.getId(), foodId, cartNum);
            req.setAttribute("msg",Const.BOOK_SUCCESS_MSG);
            req.getRequestDispatcher("/jsp/Msg.jsp").forward(req,resp);

    }
     public void deleteCart(HttpServletRequest req, HttpServletResponse resp)throws Exception{
         CartService cartService = new CartServiceImpl();
         AgentManage agentManage = new AgentManage(cartService);
         CartService agent = (CartService)agentManage.getAgent();
         String cartIdStr = req.getParameter("cartId");
         boolean autoDelete = false;
             int delete = agent.deleteCart(Integer.parseInt(cartIdStr));

             if (delete>0){
                     req.getRequestDispatcher("checkCart").forward(req,resp);
             }
     }
     public void addCartBook(HttpServletRequest req, HttpServletResponse resp) throws Exception{
         req.getSession().setAttribute("autoDelete",true);
        this.checkRealCoupon(req,resp);
     }
    public void checkBook(HttpServletRequest req, HttpServletResponse resp)throws Exception{
        BookService bookService = new BookServiceImpl();
        FoodService foodService = new FoodServiceImpl();
        AgentManage agentManage1 = new AgentManage(bookService);
        AgentManage agentManage2 = new AgentManage(foodService);
        BookService agent1 = (BookService)agentManage1.getAgent();
        FoodService agent2 = (FoodService)agentManage2.getAgent();
        User user = (User)req.getSession().getAttribute("user");

            List<Book> books = agent1.checkBook(user.getId());
            List<Food> foods = agent2.checkBookFood(books);
            req.setAttribute("books",books);
            req.setAttribute("foods",foods);
            req.getRequestDispatcher("/jsp/Book.jsp").forward(req,resp);
    }
    public void deleteBook(HttpServletRequest req, HttpServletResponse resp)throws Exception{
        BookService bookService = new BookServiceImpl();
        AgentManage agentManage1 = new AgentManage(bookService);
        BookService agent1 = (BookService)agentManage1.getAgent();
        int bookId=Integer.parseInt(req.getParameter("bookId"));

            int delete= agent1.deleteBook(bookId);
            if (delete>0){
                req.getRequestDispatcher("user/checkUserBook").forward(req,resp);
            }

    }
    public void searchShop(HttpServletRequest req, HttpServletResponse resp)throws Exception{
            req.setCharacterEncoding("utf-8");
        ShopService shopService = new ShopServiceImpl();
        AgentManage agentManage = new AgentManage(shopService);
        String checkFactor = req.getParameter("checkFactor");
        boolean matches = checkFactor.length()==0;
        if (matches){
            req.setAttribute("msg",Const.ILLEGAL_INPUT_MSG);
            try {
                req.getRequestDispatcher("/jsp/Msg.jsp").forward(req,resp);
                return;
            } catch (ServletException | IOException e) {
                e.printStackTrace();
            }
        }
        ShopService agent = (ShopService)agentManage.getAgent();
            List<Shop> shops = agent.searchShop(checkFactor);
            req.setAttribute("shops",shops);
            req.getRequestDispatcher("/jsp/SearchShop.jsp").forward(req,resp);

    }
    public void checkCoupon(HttpServletRequest req, HttpServletResponse resp)throws Exception{
       CouponService couponService = new CouponServiceImpl();
        AgentManage agentManage = new AgentManage(couponService);
        CouponService agent = (CouponService)agentManage.getAgent();
        User user = (User)req.getSession().getAttribute("user");
             Object[] objects = agent.checkCoupon(user.getId());
            req.setAttribute("coupons",objects[0]);
            req.setAttribute("shops",objects[1]);
            req.getRequestDispatcher("/jsp/checkCoupon.jsp").forward(req,resp);

    }
    public void deleteCoupon(HttpServletRequest req, HttpServletResponse resp)throws Exception{
        CouponService couponService = new CouponServiceImpl();
        AgentManage agentManage = new AgentManage(couponService);
        CouponService agent = (CouponService)agentManage.getAgent();
        int couponId = Integer.parseInt(req.getParameter("couponId"));
            int delete = agent.deleteCoupon(couponId);
            if (delete>0){

                req.getRequestDispatcher("checkCoupon").forward(req,resp);
            }
            else {
                req.setAttribute("msg",Const.DELETE_ERROR_MSG);
            }

    }
    public void addCoupon(HttpServletRequest req, HttpServletResponse resp)throws Exception{
        CouponService couponService = new CouponServiceImpl();
        AgentManage agentManage = new AgentManage(couponService);
        CouponService agent = (CouponService)agentManage.getAgent();
        int shopId = Integer.parseInt(req.getParameter("shopId"));
        User user = (User)req.getSession().getAttribute("user");
            int insert = agent.addCoupon(user.getId(),shopId);
            if (insert>0){
                req.setAttribute("msg",Const.GET_SUCCESS_MSG);
                req.getRequestDispatcher("/jsp/Msg.jsp").forward(req,resp);
            }
            else {
                req.setAttribute("msg",Const.GET_ERROR_MSG);
                req.getRequestDispatcher("/jsp/Msg.jsp").forward(req,resp);
            }

    }
    public void checkMsg(HttpServletRequest req, HttpServletResponse resp){
        MsgBoardService msgBoardService = new MsgBoardServiceImpl();
        AgentManage agentManage = new AgentManage(msgBoardService);
        MsgBoardService agent = (MsgBoardService)agentManage.getAgent();
        int shopId = Integer.parseInt(req.getParameter("shopId"));
        User user = (User) req.getSession().getAttribute("user");
        try {
            Object[] objects = agent.showMsg(shopId);
            req.setAttribute("msgBoards",objects[0]);
            req.setAttribute("replies",objects[1]);
            req.setAttribute("users",objects[2]);
            req.setAttribute("shopId",shopId);
            if (user ==null||user.getRightId()==0){
                req.getRequestDispatcher("/jsp/MsgBoard.jsp").forward(req,resp);
            }
            else {
                req.getRequestDispatcher("/jsp/MsgManage.jsp").forward(req,resp);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public void addMsg(HttpServletRequest req, HttpServletResponse resp)throws Exception{
            req.setCharacterEncoding("utf-8");
        MsgBoardService msgBoardService = new MsgBoardServiceImpl();
        AgentManage agentManage = new AgentManage(msgBoardService);
        MsgBoardService agent = (MsgBoardService)agentManage.getAgent();
        String comment = req.getParameter("comment");
        boolean matches = comment.length()>0;
        if (!matches){
            req.setAttribute("msg",Const.ILLEGAL_INPUT_MSG);
                req.getRequestDispatcher("/jsp/Msg.jsp").forward(req,resp);
                return;
        }
        int shopId = Integer.parseInt(req.getParameter("shopId"));
        int replyId = Integer.parseInt(req.getParameter("replyId"));
        User user = (User) req.getSession().getAttribute("user");
            if (user ==null){
                req.getRequestDispatcher("/jsp/login.jsp").forward(req,resp);
            }
            else {
                int addMsg = agent.addMsg(user.getId(), shopId, replyId, comment);
                if (addMsg>0&&user.getRightId()==0){
                    req.getRequestDispatcher("user/checkMsg").forward(req,resp);
                }
                else {
                    req.getRequestDispatcher("user/checkMsg").forward(req,resp);
                }
            }
    }
    public void checkUserBook(HttpServletRequest req, HttpServletResponse resp)throws Exception{
        BookService bookService = new BookServiceImpl();
        AgentManage agentManage = new AgentManage(bookService);
        BookService agent = (BookService)agentManage.getAgent();
        User user = (User)req.getSession().getAttribute("user");

            Object[] objects = agent.checkUserBook(user.getId());
            req.setAttribute("books",objects[0]);
            req.setAttribute("foods",objects[1]);
            req.getRequestDispatcher("/jsp/checkBook.jsp").forward(req,resp);
    }
    public void addCollect(HttpServletRequest req, HttpServletResponse resp) throws Exception{
        UserService userService = new UserServiceImpl();
        AgentManage agentManage = new AgentManage(userService);
        UserService agent = (UserService) agentManage.getAgent();
        int shopId = Integer.parseInt(req.getParameter("shopId"));
        User user = (User) req.getSession().getAttribute("user");
            int add = agent.addCollect(shopId, user.getId());
            if (add > 0) {
                req.setAttribute("msg", Const.ADD_SUCCESS_MSG);
                req.getRequestDispatcher("/jsp/Msg.jsp").forward(req, resp);
            }
            else {
                req.setAttribute("msg",Const.ADD_ERROR_MSG);
                req.getRequestDispatcher("/jsp/Msg.jsp").forward(req,resp);
            }
    }
    public void checkCollect(HttpServletRequest req, HttpServletResponse resp) throws Exception{
        ShopService shopService = new ShopServiceImpl();
        AgentManage agentManage = new AgentManage(shopService);
        ShopService agent = (ShopService) agentManage.getAgent();
        User user = (User) req.getSession().getAttribute("user");
            List<Shop> shops = agent.checkCollect(user.getId());
            req.setAttribute("shops",shops);
            req.getRequestDispatcher("/jsp/CollectShop.jsp").forward(req,resp);

    }
    public void deleteCollect(HttpServletRequest req, HttpServletResponse resp) throws Exception{
        UserService userService = new UserServiceImpl();
        AgentManage agentManage = new AgentManage(userService);
        UserService agent = (UserService) agentManage.getAgent();
        User user = (User) req.getSession().getAttribute("user");
        int shopId = Integer.parseInt(req.getParameter("shopId"));

            int delete = agent.deleteCollect(shopId);
            if (delete > 0){
                req.getRequestDispatcher("checkCollect").forward(req,resp);

            }
            else {
                req.setAttribute("msg",Const.DELETE_SUCCESS_MSG);
                req.getRequestDispatcher("/jsp/Msg.jsp").forward(req,resp);
            }

    }
    public void addComplaint(HttpServletRequest req, HttpServletResponse resp) throws Exception{

            req.setCharacterEncoding("utf-8");
    ComplaintService complaintService = new ComplaintServiceImpl();
    AgentManage agentManage = new AgentManage(complaintService);
        ComplaintService agent = (ComplaintService)agentManage.getAgent();
        String complaintText = req.getParameter("complaintText");
        User user = (User)req.getSession().getAttribute("user");
            int add = agent.addComplaint(complaintText, user.getId());
            if (add>0){
                req.setAttribute("msg",Const.FEEDBACK_SUCCESS_MSG);
                req.getRequestDispatcher("/jsp/Msg.jsp").forward(req,resp);
            }
            else {
                req.setAttribute("msg",Const.FEEDBACK_ERROR_MSG);
                req.getRequestDispatcher("/jsp/Msg.jsp").forward(req,resp);
            }
    }
    public void addShopStar(HttpServletRequest req, HttpServletResponse resp)throws Exception{
        ShopService shopService = new ShopServiceImpl();
        AgentManage agentManage = new AgentManage(shopService);
        ShopService agent = (ShopService) agentManage.getAgent();
        int shopId = Integer.parseInt(req.getParameter("shopId"));
            int update = agent.updateStar(shopId);
            if (update>0){
                req.getRequestDispatcher("showShop").forward(req,resp);
            }
    }
    public void exitLogin(HttpServletRequest req, HttpServletResponse resp)throws Exception{
        Cookie[] cookies = req.getCookies();
        for (Cookie c: cookies) {
            c.setMaxAge(0);
            resp.addCookie(c);
        }
        req.getSession().removeAttribute("user");
            resp.sendRedirect("../jsp/login.jsp");
    }
    public void isAutoLogin(HttpServletRequest req, HttpServletResponse resp) throws Exception{
        Cookie[] cookies = req.getCookies();
        boolean flag1 = false;
        boolean flag2 = false;
        if (cookies!=null){
            for (Cookie c : cookies) {
                switch (c.getName()) {
                    case "username":
                        flag1 = true;
                        break;
                    case "password":
                        flag2 = true;
                        break;
                    default:
                        break;
                }
            }
        }
        if (flag1&&flag2){
            try {
                req.getRequestDispatcher("login").forward(req,resp);
            } catch (ServletException | IOException e) {
                e.printStackTrace();
            }
        }
        else {
                req.getRequestDispatcher("../jsp/login.jsp").forward(req,resp);
        }
    }
    public void checkRealCoupon(HttpServletRequest req, HttpServletResponse resp) throws Exception{
        CouponService couponService = new CouponServiceImpl();
        AgentManage agentManage= new AgentManage(couponService);
        CouponService agent = (CouponService)agentManage.getAgent();
        User user = (User)req.getSession().getAttribute("user");
        int foodId = Integer.parseInt(req.getParameter("foodId"));

            List<Coupon> coupons = agent.checkShopCoupon(user.getId(), foodId);
            coupons.removeIf(coupon ->
                    coupon.getExpirationTime().compareTo
                            (new Timestamp(System.currentTimeMillis())) < 0);
            if (coupons.size()>0){
                req.setAttribute("foodId",req.getParameter("foodId"));
                req.setAttribute("dishNum",req.getParameter("dishNum"));
                req.setAttribute("shopId",req.getParameter("shopId"));
                req.getRequestDispatcher("../jsp/UseCoupon.jsp").forward(req,resp);
            }
            else {
                req.setAttribute("price",0.0);
                req.setAttribute("foodId",req.getParameter("foodId"));
                req.setAttribute("dishNum",req.getParameter("dishNum"));
                req.setAttribute("shopId",req.getParameter("shopId"));
                req.getRequestDispatcher("addBook").forward(req,resp);
            }

    }
    public void refreshMoney(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        UserService userService = new UserServiceImpl();
        AgentManage agentManage = new AgentManage(userService);
        UserService agent = (UserService)agentManage.getAgent();
        User user = (User) req.getSession().getAttribute("user");
        User user1 = agent.checkUser(user.getId());
        req.getSession().setAttribute("user",user1);
        if (user1.getRightId()==0){
            req.getRequestDispatcher("../jsp/UserCenter.jsp").forward(req,resp);
        }
        else {
            req.getRequestDispatcher("../jsp/BusinessCenter.jsp").forward(req,resp);
        }

    }
 }


